// src/directives/permission.js
import { useUserStore } from '@/stores/userStore'

/**
 * 权限指令
 * 使用方式：
 * v-permission="'system:user:view'"
 * v-permission="['system:user:view', 'system:user:manage']"
 * v-permission.any="['system:user:view', 'system:user:manage']"  // 任一权限满足
 * v-permission.all="['system:user:view', 'system:user:manage']"  // 所有权限满足
 */
export const permission = {
  mounted(el, binding) {
    const { value, modifiers } = binding
    
    if (!value) return
    
    const userStore = useUserStore()
    
    // 超级管理员拥有所有权限
    if (userStore.isAdmin) {
      return
    }
    
    let hasPermission = false
    
    if (Array.isArray(value)) {
      if (modifiers.all) {
        // 检查所有权限
        hasPermission = value.every(p => userStore.permissions.includes(p))
      } else {
        // 检查任一权限（默认）
        hasPermission = value.some(p => userStore.permissions.includes(p))
      }
    } else {
      // 单个权限检查
      hasPermission = userStore.permissions.includes(value)
    }
    
    if (!hasPermission) {
      // 隐藏元素
      el.style.display = 'none'
      // 或者移除元素
      // el.remove()
    }
  },
  
  updated(el, binding) {
    // 重新检查权限
    const { value, modifiers } = binding
    
    if (!value) return
    
    const userStore = useUserStore()
    
    // 超级管理员拥有所有权限
    if (userStore.isAdmin) {
      el.style.display = ''
      return
    }
    
    let hasPermission = false
    
    if (Array.isArray(value)) {
      if (modifiers.all) {
        hasPermission = value.every(p => userStore.permissions.includes(p))
      } else {
        hasPermission = value.some(p => userStore.permissions.includes(p))
      }
    } else {
      hasPermission = userStore.permissions.includes(value)
    }
    
    if (!hasPermission) {
      el.style.display = 'none'
    } else {
      el.style.display = ''
    }
  }
}

/**
 * 角色指令
 * 使用方式：
 * v-role="'ROLE_ADMIN'"
 * v-role="['ROLE_ADMIN', 'ROLE_MANAGER']"
 */
export const role = {
  mounted(el, binding) {
    const { value } = binding
    
    if (!value) return
    
    const userStore = useUserStore()
    
    let hasRole = false
    
    if (Array.isArray(value)) {
      hasRole = value.some(r => userStore.roles.includes(r))
    } else {
      hasRole = userStore.roles.includes(value)
    }
    
    if (!hasRole) {
      el.style.display = 'none'
    }
  },
  
  updated(el, binding) {
    const { value } = binding
    
    if (!value) return
    
    const userStore = useUserStore()
    
    let hasRole = false
    
    if (Array.isArray(value)) {
      hasRole = value.some(r => userStore.roles.includes(r))
    } else {
      hasRole = userStore.roles.includes(value)
    }
    
    if (!hasRole) {
      el.style.display = 'none'
    } else {
      el.style.display = ''
    }
  }
} 